# 服务器接收数据线程
import socket
import json
import struct

import socket
import time
from PyQt5.QtCore import QThread, pyqtSignal

pkg_len = 326

HEADER_LEN = 4
tail_LEN = 2
# payload_len = 270
payload_len = 320

def drain_startup_garbage(conn: socket.socket, drain_timeout: float = 0.2) -> None:
    """Read and discard any buffered data before structured messages."""

    original_timeout = conn.gettimeout()
    print(original_timeout)
    if original_timeout is None:
        conn.settimeout(0.5)
    
    discarded_total = 0
    try:
        while True:
            try:
                data = conn.recv(4096)
                print(len(data))
            except socket.timeout:
                break

            if not data:
                break

            discarded_total += len(data)

            # If the peer is flooding garbage, allow socket.timeout to break the loop.
    finally:
        conn.settimeout(original_timeout)

    if discarded_total:
        print(f"discarded {discarded_total} bytes of pre-handshake garbage")


def recv_exact(conn, n):
    data = bytearray()
    status = 0
    while len(data) < n:
        # print('-')
        try:
            chunk = conn.recv(n - len(data),)
            if not chunk:
                print('error -- --')
            # raise ConnectionError("client disconnected")
            data.extend(chunk)
        except socket.timeout:
            status = 1
            break

         

    return (status, bytes(data))

def deal_header(header):
    # print(header)
    if (header[0]==0xA5) & (header[1]==0xA5):
        return 0
    else:
        return 1
    # pass

def deal_tail(header):
    # print(header)
    pass

def convert_byte_to_bin(byte):
    return ''.join(format(byte,'08b'))

def deal_payload(data):
    pass


class TcpReceiverThread(QThread):
    data_received_header = pyqtSignal(bytes) 
    data_received_tail = pyqtSignal(bytes) 
    data_received_payload = pyqtSignal(bytes) 

    def __init__(self, host, port):
        super().__init__()
        self.host = host
        self.port = port

        self._running = True  




    def run(self):
        server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        # server.bind(('192.168.0.24', 6002)) 
        # server.bind(('192.168.43.9', 6002)) 
        server.bind((self.host, self.port)) 

        server.listen(1)        # 创建并绑定 TCP 服务器
        client, addr = server.accept()
        print(f"connected : {addr}")

        cmd = { 'cmd' :'stop recording'}
        cmd_json = json.dumps(cmd)
        client.send(cmd_json.encode('utf-8'))  # 开始记录

        time.sleep(1) # 暂停1秒

        drain_startup_garbage(client)

        client.settimeout(5)

        print('new recording begin')

        cmd = { 'cmd' :'start recording'}
        cmd_json = json.dumps(cmd)

        client.send(cmd_json.encode('utf-8'))  # 开始记录


        while self._running:

            (status,header) = recv_exact(client, HEADER_LEN)
            if status :
                continue

            if deal_header(header):
                continue

            # self.data_received_header.emit(header) 

            (status,payload) = recv_exact(client, payload_len)
            # deal_payload(payload)
            if status :
                continue

            self.data_received_payload.emit(payload) 

            (status,tail) = recv_exact(client, tail_LEN)
            # deal_tail(tail)
            if status :
                continue
            # self.data_received_tail.emit(tail) 

    def stop(self):
        """停止线程的运行"""
        self._running = False  # 设置标记为 False
        self.quit()  # 请求线程退出
        self.wait()  # 等待线程退出
        print('tcp thread stop')


        # client.close()
        # server.close()